const redis = require('redis')
const {REDIS_CONF} =require('../conf/db')

const redisClient = redis.createClient(REDIS_CONF.prot,REDIS_CONF.host) //创建客户端

redisClient.on('error',err=>{//监听错误
    console.log(err)
})

function redisSet(key,val){
    if(typeof val === Object){
        val.toString()
    }
    redisClient.set(key,val,redis.print) //redis.print会返回是否正确
}

function redisGet(key){
    let promise = new Promise((resolve,reject)=>{
        redisClient.get(key,(err,val)=>{
            console.log('err',err)
            if(err){
                reject(err)
            }
            if(val == null){
                resolve(null)
            }
            try{
                resolve(
                    JSON.parse(val)
                )
            }catch(ex){
                resolve(val)
            }
            console.log('val',val)
            redisClient.quit()
        })
    })
    return promise
}
module.exports = {
    redisSet,
    redisGet
}
